<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Http\Exports\WithdrawalsExport;
use App\Http\Forms\WithdrawalCertForm;
use App\Modules\Comment\Models\Comment;
use App\Modules\Order\Models\Order;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\User;
use App\Modules\Withdrawal\Models\BankInfo;
use App\Modules\Withdrawal\Models\Withdrawal;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WithdrawalController extends ApiController
{
    public function index(Request $request)
    {
        //更新提现管理的对应关系
//        $collection = Withdrawal::query()->get(["order_id", "id", "shop_id"]);
//        foreach ($collection as $c) {
//            $model = Order::query()->whereIn("id", $c->order_id)->get()->toArray();
//            $array_column = array_column($model, "shop_id");
//            $array_column = array_unique($array_column);
//            $array_column = array_merge($array_column,[]);
////            $explode = implode($array_column, ",");
//            Withdrawal::query()->where("id", $c->id)->update(["shop_id" => $array_column]);
//        }
//        dd("同步数据库结束");
        $this->authorize('withdrawal');
        $search = $request->input('search');//用户名
        $orderId = $request->input('order_id');

        //起止时间
        $start = $request->input('start');
        $end = $request->input('end');

        //提现人
        $txName = $request->input('tx_name');
        //提现的状态
        $isSuccess = $request->input('is_success');
        //商铺id
        $shopId = $request->input('shop_id', '');
        $shopName = $shopId ? Shop::query()->where('id', $shopId)->first('name')->name : '';
        $export = $request->input('export', 0);

//        DB::connection()->enableQueryLog();  // 开启QueryLog

        $query = Withdrawal::query()
            ->join('users', 'users.id', '=', 'withdrawals.user_id')
            ->leftJoin("bank_infos as bi", "bi.id", '=', 'withdrawals.link_id')
            ->orderBy('withdrawals.created_at', 'desc');

        if (!empty($shopId)) {
            $query->whereJsonContains('withdrawals.shop_id', (int)$shopId);
//            $query->whereRaw("find_in_set({$shopId}, withdrawals.shop_id)");
        }

        if (!empty($start)) {
            $query->where('withdrawals.created_at', '>', $start);
        }
        if (!empty($end)) {
            $query->where('withdrawals.created_at', '<', Carbon::parse($end)->addDay()->toDateString());
        }

        if (!empty($search)) {
            $query->where('users.name', 'like', '%' . $search . '%');
        }

        if (!empty($txName)) {
            $query->where('bi.name', 'like', '%' . $txName . '%');
        }

        if (!empty($isSuccess)) {
            $query->where('withdrawals.status', $isSuccess);
        }

        if (!empty($orderId)) {
            $query->whereJsonContains('withdrawals.order_id', (int)$orderId);
        }

        if ($export) {
            $data = $query
                ->select('withdrawals.*', 'users.name', 'users.nickname', 'users.avatar', 'bi.name as tx_name', 'bi.no', 'bi.bank_name')
                ->get()
                ->map(function ($item) {
                    return [
                        $item->name, $item->tx_name, $item->bank_name,
                        $item->no, Withdrawal::$statusShow[$item->status],
                        $item->created_at, implode($item->order_id, ",")
                    ];
                });
            return (new WithdrawalsExport("提现订单.xlsx", $data->all()))->downLoad();
        }

        $data = $query
            ->select('withdrawals.*', 'users.name', 'users.avatar', 'bi.name as tx_name', 'bi.no', 'bi.bank_name')
            ->paginate(20);
//        dd(DB::getQueryLog());

        //数量
        $count = $query->count();
        //订单总金额
        $money = $query->sum("money") / 100;
        //商家
        $allShop = Shop::query()->get();

//        $bankInfo = BankInfo::query()
//            ->withTrashed()
//            ->whereIn('id', $data->pluck('link_id')->all())
//            ->get()
//            ->keyBy('id');


        return view('withdrawal.index', compact('data', 'money', 'count', 'shopId', 'shopName', 'allShop', 'isSuccess', 'txName', 'start', 'end', 'search', 'orderId'));
    }

    public function check()
    {

    }

    public function certificate($id)
    {
        $this->authorize('withdrawal-edit');
        $withdrawal = Withdrawal::query()->find($id);
        $form = $this->form(WithdrawalCertForm::class, [
            'method' => 'POST',
            'url' => route('admin.withdrawal.finish', ['id' => $id]),
            'model' => $withdrawal
        ]);
        return view('withdrawal.form', compact('form'));
    }

    public function finish($id)
    {
        $this->authorize('withdrawal-edit');
        $form = $this->form(WithdrawalCertForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $withdrawal = Withdrawal::query()
            ->where('id', $id)
//            ->where('status', Withdrawal::STATUS_INIT)
            ->first();
        $withdrawal->update([
            'status' => Withdrawal::STATUS_SUCCESS,
            'certificate' => $data['certificate'],
        ]);
        Rebate::query()
            ->whereIn('id', $withdrawal->rebate_id)
            ->update([
                'withdrawal_status' => Rebate::WITHDRAWAL_STATUS_SUCCESS,
            ]);
        /**
         *  临洮：打款成功
         *  模板ID：q_Tusmt0Jzbg0XADplKd3avfqC9G3WWrmD9FUKL0iQA
         *  格式：
         * {{first.DATA}}
         * 提现金额：{{keyword1.DATA}}
         * 申请时间：{{keyword2.DATA}}
         * 审核状态：{{keyword3.DATA}}
         * 原因说明：{{keyword4.DATA}}
         * 时间：{{keyword5.DATA}}
         * {{remark.DATA}}
         */
        $user = User::query()->find($withdrawal->id);
        $sendData = [
            $user->openid,
            ($withdrawal->money / 100) . "元",
            date("Y年m月d日 H时i分s秒", strtotime($withdrawal->created_at)),
            "已打款",
            "无",
            date("Y年m月d日 H时i分s秒")
        ];
        sendMessage(30,$sendData);
        return redirect()->route('admin.withdrawal.index');
    }
}
